//
//  LoginViewController.m
//  UEAssistant
//
//  Created by haoxiang on 17/1/22.
//  Copyright © 2017年 youyixinxi. All rights reserved.
//

#import "LoginViewController.h"
#import "NSString+checklogin.h"
#import "NSString+RandomString.h"
#import "TempDataView.h"
#import "TabbarController.h"
#import "OrderBaseControl.h"
#import "NavigationController.h"
#import "LeftSortsViewController.h"
#import "MJ_UserLoginViewModel.h"
#import "MJ_UserLoginUserLoginDetail.h"
#import "MJ_TaskViewController.h"
#import <MMDrawerController/MMDrawerController.h>
#import "MJ_UserMessage.h"
#import "IPhoneType.h"
@interface LoginViewController ()<UIViewControllerTransitioningDelegate,UITextFieldDelegate>{
    
    CGFloat   _deltaY;
}

@property (nonatomic, strong) UIView                    *backView;
@property (nonatomic, strong) UIImageView               *logoView;
@property (nonatomic, strong) UITextField               *accountField;
@property (nonatomic, strong) UITextField               *passwordField;
@property (nonatomic, strong) UILabel                   *accoLabel;
@property (nonatomic, strong) UILabel                   *passLabel;
@property (nonatomic, strong) UIView                    *accoLine;
@property (nonatomic, strong) UIView                    *passLine;
@property (nonatomic, strong) UIButton                  *loginBt;
@property (nonatomic, strong) UIButton                  *accountBt;
@property (nonatomic, strong) UIButton                  *passwordBt;
@property (nonatomic, strong) UILabel                   *LoginLabel;
@property (nonatomic, strong) UIImageView               *accountSureV;
@property (nonatomic, strong) UIButton                  *showPassBt;
@property (nonatomic, strong) UIView                    *coverView;

//登录ViewModel
@property (strong, nonatomic)MJ_UserLoginViewModel *viewModel;
@end

@implementation LoginViewController

-(MJ_UserLoginViewModel *)viewModel {
    if (!_viewModel) {
        _viewModel = [[MJ_UserLoginViewModel alloc] init];
    }
    return _viewModel;
}

- (void)viewWillAppear:(BOOL)animated{
    
    [self.navigationController.navigationBar setHidden:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [self.navigationController.navigationBar setHidden:NO];
    for (UIView *view in self.view.subviews) {
        [view removeFromSuperview];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initlizeUserface];
    [self initlizeDataSourece];
}


#pragma mark -******  init  ******-----------

- (void)initlizeUserface{

    self.view.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.accoLabel];
    [self.view addSubview:self.accoLine];
    [self.view addSubview:self.passLabel];
    [self.view addSubview:self.passLine];
    [self.view addSubview:self.accountBt];
    [self.view addSubview:self.passwordBt];
    [self.view addSubview:self.accountField];
    [self.view addSubview:self.passwordField];
    [self.view addSubview:self.loginBt];
    [self.view addSubview:self.LoginLabel];
    [self.view addSubview:self.showPassBt];
    
}

- (void)initlizeDataSourece{
    [UserDefaults removeObjectForKey:@"timeRange"];//移除登录超时统计数据
    [userManager checkAppVersion];
}

#pragma private

- (UIStatusBarStyle)preferredStatusBarStyle{
    
    return UIStatusBarStyleDefault;
}

- (void)loginSuccessTopushVC:(UIButton *)sender{
    
    [self.loginBt setEnabled:NO];
    [self.view endEditing:YES];

    if (self.accountField.text.length == 0 || self.passwordField.text.length == 0) {
        [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"账号密码不能为空" andTitleColor:[UIColor whiteColor] andCancel:YES];
        [self.loginBt setEnabled:YES];
    }
    else{
        [self.view addSubview:self.coverView];
        [LSProgressHUD showLoadingToView:self.view];
        
        //随机生成32位Cookie
        [UserDefaults setObject:[NSString getRandomStringWithNum:32] forKey:@"User_Cookie"];
        TGLog(@"登录界面Cookie = %@",[UserDefaults objectForKey:@"User_Cookie"]);
//
        NSDictionary *params;
//        if (![UserDefaults objectForKey:@"deviceToken"]) {
//            [UserDefaults setObject:@"tempToken" forKey:@"deviceToken"];
//        }
//        NSString *uuidString = [[[UIDevice currentDevice].identifierForVendor UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
//
        params = @{@"userName":self.accountField.text,
                   @"userPwd":self.passwordField.text,
                   @"deviceToken":[userManager getDeviceToken],
                   @"deviceModel":[IPhoneType iphoneType]
                   };
        TGLog(@"参数:%@",params);
        //初始化登录后判定用户状态做出相应UI操作
        __weak typeof(self) weakSelf = self;
        [self.viewModel initializeLoginWithParameter:params Result:^(BOOL success) {
            [self.loginBt setEnabled:YES];
            [self.coverView removeFromSuperview];
            [LSProgressHUD hiddenLoading:self.view];
            if (success) {
                //缓存数据操作
                MJ_UserLoginUserLoginDetail *userDetail = weakSelf.viewModel.resultModel.userLoginDetail;
                NSInteger userType = userDetail.userType;
                //判断用户类别，显示各自权限内容
                switch (userType) {
                    case 1:
                        //1.2为企业管理者界面
                        [self setupEnterpriseManagerRootViewController];
                        userManager.urlCategate = @"/enterprise";
                        break;
                    case 2:
                        [self setupEnterpriseManagerRootViewController];
                        userManager.urlCategate = @"/enterprise";
                        break;
                    case 3:
                        //私有译员（企业版私有用户）（任务：待抢单，进行中）
                        [self setupPriviteRootViewController];
                        userManager.urlCategate = @"/enterprise";
                        break;
                    case 4:
                        //个人版 （来自客户、来自平台区分，在controller中判定）
                        [self setupPriviteRootViewController];
                        userManager.urlCategate = @"/personal";
                        break;
                    case 5://（过期的owner）个人版
                        [self setupPriviteRootViewController];
                        userManager.urlCategate = @"/personal";
                        break;
                    default://6,7 : 无效用户
                        userManager.urlCategate = @"/personal";
                        break;
                }
            }else{
               //登录失败
            }
        }];
    }
}
//企业管理者
- (void)setupEnterpriseManagerRootViewController {
    MMDrawerController *mmdrawer = [[MJ_UserMessage sharedInstance] setupEnterpriseRootVC];
    [UIApplication sharedApplication].keyWindow.rootViewController = mmdrawer;
}

//私有译员(企业版和个人版)
- (void)setupPriviteRootViewController {
    MMDrawerController *mmdrawer = [[MJ_UserMessage sharedInstance] setupPriviteRootVC];
    [UIApplication sharedApplication].keyWindow.rootViewController = mmdrawer;
}


#pragma uitextFiledDelegate

- (void)textFieldDidBeginEditing:(UITextField *)textField{
    
    [self.accountSureV removeFromSuperview];
    _accoLine.backgroundColor = RGB(210, 210, 210, 1);
    
}

- (void)textFieldDidEndEditing:(UITextField *)textField{
    
    if (self.accountField.text.length != 0) {
        //去除占位符
        NSString *str =  [self.accountField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
        if ([str containsString:@"@"]) {
            
            if (![str checkEmail]) {
                [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"请输入正确的邮箱地址" andTitleColor:[UIColor whiteColor] andCancel:YES];
                [_accoLine setBackgroundColor:RGB(237, 146, 146, 1)];
            }
            else{
                [self.view addSubview:self.accountSureV];
                self.loginBt.backgroundColor = RGB(0, 118, 255, 1);
                [self.loginBt setEnabled:YES];
            }
        }
        else{
            
            if (![str checkPhone]) {
                [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"请输入正确的手机号码" andTitleColor:[UIColor whiteColor] andCancel:YES];
                [_accoLine setBackgroundColor:RGB(237, 146, 146, 1)];
            }
            else{
                [self.view addSubview:self.accountSureV];
                self.loginBt.backgroundColor = RGB(0, 118, 255, 1);
                [self.loginBt setEnabled:YES];
            }
        }
    }
}
#pragma mark -- touchesBegan
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
}

- (void)showPassWordResponds{
    
    self.showPassBt.selected = !self.showPassBt.selected;
    if (self.showPassBt.selected) {
        self.passwordField.secureTextEntry = NO;
    }else{
        self.passwordField.secureTextEntry = YES;
    }
}

#pragma mark -******  getter  ******-----------

- (UIView *)backView{
    
    if (!_backView) {
        _backView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 80*Radio, 80*Radio)];
        _backView.center = CGPointMake(self.view.center.x, self.view.center.y - 210*Radio);
        if (Screen_Width == 320) {
            _backView.center = CGPointMake(self.view.center.x, self.view.center.y - 210*Radio+30);
        }
        _backView.backgroundColor = [UIColor colorWithWhite:1 alpha:1];
        _backView.layer.shadowColor = [UIColor blackColor].CGColor;
        _backView.layer.shadowOffset = CGSizeMake(0, 0);
        _backView.layer.shadowOpacity = 0.6;
        _backView.layer.shadowRadius = 12.0*Radio;
    }
    return _backView;
}

- (UIImageView *)logoView{
    
    if (!_logoView) {
        _logoView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 90*Radio, 90*Radio)];
        _logoView.center = CGPointMake(self.view.center.x, self.view.center.y - 210*Radio);
        if (Screen_Width == 320) {
            _logoView.center = CGPointMake(self.view.center.x, self.view.center.y - 210*Radio+30);
        }
        _logoView.image = [UIImage imageNamed:@"UE_logo"];
        _logoView.layer.cornerRadius = 10*Radio;
        _logoView.layer.masksToBounds = YES;
    }
    return _logoView;
}

- (UILabel *)accoLabel{
    
    if (!_accoLabel) {
        if (Screen_Width == 414) {
            _accoLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, (Screen_Height/2-130)*Radio-70, 150, 20*Radio)];
        }else{
            _accoLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, (Screen_Height/2-110)*Radio-70, 150, 20*Radio)];
        }
        if (Screen_Width == 320) {
            _accoLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, (Screen_Height/2-110)*Radio+100-100, 150, 20*Radio)];
        }
        _accoLabel.backgroundColor = [UIColor clearColor];
        _accoLabel.text = @"手机号码/邮箱地址";
        _accoLabel.textColor = RGB(51, 51, 51, 1);
        _accoLabel.font = [UIFont systemFontOfSize:FLEXIBLE(15)];
    }
    return _accoLabel;
}

- (UILabel *)passLabel{
    
    if (!_passLabel) {
        if (Screen_Width == 414) {
            _passLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, (Screen_Height/2-50)*Radio-50+10-20, 50, 20*Radio)];
        }else{
            _passLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, (Screen_Height/2-30)*Radio-50+10-20, 50, 20*Radio)];
        }
        if (Screen_Width == 320) {
            _passLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, (Screen_Height/2-30)*Radio+100-70-20, 50, 20*Radio)];
        }
        _passLabel.backgroundColor = [UIColor clearColor];
        _passLabel.text = @"密码";
        _passLabel.textColor = RGB(51, 51, 51, 1);
        _passLabel.font = [UIFont systemFontOfSize:FLEXIBLE(15)];
    }
    return _passLabel;
}

- (UIView *)accoLine{
    
    if (!_accoLine) {
        _accoLine = [[UIView alloc]initWithFrame:CGRectMake(30, self.accoLabel.frame.origin.y+self.accoLabel.frame.size.height+50, Screen_Width-60, 1)];
        if (Screen_Width == 320) {
            _accoLine = [[UIView alloc]initWithFrame:CGRectMake(30, self.accoLabel.frame.origin.y+self.accoLabel.frame.size.height+40, Screen_Width-60, 1)];
        }
        _accoLine.backgroundColor = RGB(210, 210, 210, 1);
    }
    return _accoLine;
}

- (UIView *)passLine{
    
    if (!_passLine) {
        _passLine = [[UIView alloc]initWithFrame:CGRectMake(30, self.passLabel.frame.origin.y+self.passLabel.frame.size.height+50, Screen_Width-60, 1)];
        if (Screen_Width == 320) {
            _passLine = [[UIView alloc]initWithFrame:CGRectMake(30, self.passLabel.frame.origin.y+self.passLabel.frame.size.height+40, Screen_Width-60, 1)];
        }
        _passLine.backgroundColor = RGB(210, 210, 210, 1);
    }
    return _passLine;
}

- (UITextField *)accountField{
    
    if (!_accountField) {
        _accountField = [[UITextField alloc]initWithFrame:CGRectMake(30, self.accoLabel.frame.origin.y+self.accoLabel.frame.size.height+5, Screen_Width-60, 40)];
        if (Screen_Width == 320) {
            _accountField = [[UITextField alloc]initWithFrame:CGRectMake(30, self.accoLabel.frame.origin.y+self.accoLabel.frame.size.height+5, Screen_Width-60, 40)];
        }
        _accountField.delegate = self;
        _accountField.textAlignment = NSTextAlignmentLeft;
        _accountField.backgroundColor = [UIColor clearColor];
        _accountField.borderStyle = UITextBorderStyleNone;
        _accountField.textColor = [UIColor blackColor];
        _accountField.font = [UIFont boldSystemFontOfSize:FLEXIBLE(22)];
        if (Screen_Width == 320) {
            _accountField.font = [UIFont boldSystemFontOfSize:FLEXIBLE(20)];
        }
    }
    return _accountField;
}

- (UITextField *)passwordField{
    
    if (!_passwordField) {
        _passwordField = [[UITextField alloc]initWithFrame:CGRectMake(30, self.passLabel.frame.origin.y+self.passLabel.frame.size.height+5, Screen_Width-60, 40)];
        if (Screen_Width == 320) {
            _passwordField = [[UITextField alloc]initWithFrame:CGRectMake(30, self.passLabel.frame.origin.y+self.passLabel.frame.size.height+5, Screen_Width-60, 40)];
        }
        _passwordField.textAlignment = NSTextAlignmentLeft;
        _passwordField.backgroundColor = [UIColor clearColor];
        _passwordField.borderStyle = UITextBorderStyleNone;
        _passwordField.textColor = [UIColor blackColor];
        _passwordField.secureTextEntry = YES;
        _passwordField.font = [UIFont boldSystemFontOfSize:FLEXIBLE(22)];
        if (Screen_Width == 320) {
            _passwordField.font = [UIFont boldSystemFontOfSize:FLEXIBLE(20)];
        }
    }
    return _passwordField;
}

- (UIButton *)loginBt{
    
    if (!_loginBt) {
        _loginBt = [UIButton buttonWithType:UIButtonTypeSystem];
        _loginBt.frame = CGRectMake(30, self.passLine.frame.origin.y + 25, Screen_Width-60, 50*Radio);
        _loginBt.backgroundColor = RGB(0, 118, 255, 0.3);
        [_loginBt setEnabled:NO];
        [_loginBt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _loginBt.titleLabel.font = [UIFont boldSystemFontOfSize:FLEXIBLE(18)];
        [_loginBt setTitle:@"登录" forState:UIControlStateNormal];
        _loginBt.layer.cornerRadius = 3;
        _loginBt.layer.masksToBounds = YES;
        [_loginBt addTarget:self action:@selector(loginSuccessTopushVC:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBt;
}

- (UILabel *)LoginLabel{
    
    if (!_LoginLabel) {
        if (Screen_Width == 414) {
            _LoginLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 100, 100, 50)];
        }
        else if (Screen_Width == 320){
            _LoginLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 70, 100, 50)];
            
        }else{
            _LoginLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 70, 100, 50)];
            
        }
        _LoginLabel.backgroundColor = [UIColor clearColor];
        _LoginLabel.text = @"登录";
        _LoginLabel.font = [UIFont systemFontOfSize:FLEXIBLE(30)];
        _LoginLabel.textAlignment = NSTextAlignmentLeft;
        _LoginLabel.textColor = RGB(0, 118, 255, 1);
    }
    return _LoginLabel;
}

- (UIButton *)showPassBt{
    
    if (!_showPassBt) {
        _showPassBt = [UIButton buttonWithType:UIButtonTypeCustom];
        _showPassBt.frame = CGRectMake(self.passwordField.frame.origin.x+self.passwordField.frame.size.width-16*Radio, self.passwordField.frame.origin.y+self.passwordField.frame.size.height/2-20*Radio/2, 20*Radio, 20*Radio);
        _showPassBt.backgroundColor = [UIColor clearColor];
        [_showPassBt setImage:[UIImage imageNamed:@"闭"] forState:UIControlStateNormal];
        [_showPassBt setImage:[UIImage imageNamed:@"开"] forState:UIControlStateSelected];
        [_showPassBt addTarget:self action:@selector(showPassWordResponds) forControlEvents:UIControlEventTouchUpInside];
    }
    return _showPassBt;
}

- (UIImageView *)accountSureV{
    
    if (!_accountSureV) {
        _accountSureV = [[UIImageView alloc]initWithFrame:CGRectMake(self.accountField.frame.origin.x+self.accountField.frame.size.width-16*Radio, self.accountField.frame.origin.y+self.accountField.frame.size.height/2-20*Radio/2, 20*Radio, 20*Radio)];
        _accountSureV.image = [UIImage imageNamed:@"正确"];
    }
    return _accountSureV;
}

- (UIView *)coverView{
    
    if (!_coverView) {
        _coverView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height)];
        _coverView.backgroundColor = [UIColor colorWithWhite:0.3 alpha:0.5];
    }
    return _coverView;
}

@end

